from django.shortcuts import HttpResponse, redirect, render
from web.forms.wiki import add_edit
from django.http import JsonResponse
from web import models
from django.shortcuts import reverse
from web.forms.wiki import add_edit
# 图片上传
from django.views.decorators.csrf import csrf_exempt
from utils.tencent import cos
from utils.Md5 import uid


def wiki(request, project_id):
    '''wiki'''
    wiki_id = request.GET.get('wiki_id')
    if wiki_id and wiki_id.isdecimal():
        wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
        return render(request, 'wiki.html', locals())
    return render(request, 'wiki.html')


def wiki_add(request, project_id):
    '''wiki文章添加'''
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        form = add_edit(request)
        return render(request, 'wiki_add.html', locals())
    form = add_edit(request, data=request.POST)
    if form.is_valid():
        # 手动赋值
        form.instance.project = request.tracer.project
        # 获取depth 如果没有parent_id，默认等于1，如果有加一
        if form.instance.parent:
            # 自加一
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        # 保存数据
        form.save()
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


def multilevel_directory(request, project_id):
    '''多级目录'''
    wiki_obj = models.Wiki.objects.filter(project_id=project_id).values('parent_id', 'title', 'id').order_by('depth')
    # wiki_obj = models.Wiki.objects.filter(project_id=project_id).values_list('parent_id', 'title')
    # print(wiki_obj)
    return JsonResponse({'data': list(wiki_obj)})


def wiki_delete(request, project_id):
    '''wiki删除'''
    # 通过wiki_id进行判断当前是哪一篇文章
    wiki_id = request.GET.get('wiki_id')
    if wiki_id and wiki_id.isdecimal():
        wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
        return render(request, 'wiki.html')
    return render(request, 'wiki.html')


def wiki_edit(request, project_id, wiki_id):
    '''wiki编辑'''
    dic = {
        'status': 1,
        'msg': ''
    }
    # 通过wiki_id进行判断当前是哪一篇文章
    # wiki_id----wiki.html--本质是wiki view传送的 传送过来的
    if wiki_id and wiki_id.isdecimal():  # 这一句判断可以没有，
        wiki_obj = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
        if request.method == 'GET':
            form = add_edit(request, instance=wiki_obj)
            return render(request, 'wiki_edit.html', locals())
        form = add_edit(request, data=request.POST, instance=wiki_obj)
        if form.is_valid():
            # 手动赋值
            form.instance.project = request.tracer.project
            # 获取depth 如果没有parent_id，默认等于1，如果有加一
            if form.instance.parent:
                # 自加一
                form.instance.depth = form.instance.parent.depth + 1
            else:
                form.instance.depth = 1
            # form.save() 会自动把数据库没有的字段进行剔除，并保存需要的字段
            form.save()
            return JsonResponse(dic)
        dic['status'] = 0
        dic['msg'] = form.errors
        return JsonResponse(dic)
    return render(request, 'wiki.html')


@csrf_exempt
def upload_img(request, project_id):
    result = {
        'success': 0,
        'message': None,
        'url': None
    }
    # print(request.FILES)
    # < MultiValueDict: {'editormd-image-file': [ < InMemoryUploadedFile: 5.png(image / png) >]} >
    editormd_image_file = request.FILES.get('editormd-image-file')
    if not editormd_image_file:
        result['message'] = '文件不存在'
        return JsonResponse(result)
    # 有文件
    # 上传图片路径拼接 editormd_image_file 是一个对象
    suffix = editormd_image_file.name.split('.')[-1]  # png
    Bucket = request.tracer.project.bucket
    region = request.tracer.project.region
    Body = editormd_image_file
    Key = '{}.{}'.format(uid(request.tracer.user.telephone), suffix)
    # 进行cos存储
    # 返回一个url----返回给前端展示出来
    url = cos.upload_img(Bucket=Bucket, region=region, Body=Body, Key=Key)
    result['success'] = 1
    result['url'] = url
    print(url)
    return JsonResponse(result)
